﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;


namespace CommonUtil
{
    public enum LogType
    {
        Debug = 4,
        Error = 3,
        Information = 1,
        Warning = 2,
    }

    public class Logger
    {
        //日志目录
		private string _logdirdest;
        private static string LogDir;

        #region 构造函数
        static Logger()
        {
            LogDir = System.AppDomain.CurrentDomain.BaseDirectory + "log\\";
            if (!Directory.Exists(LogDir))
            {
                Directory.CreateDirectory(LogDir);
            }
        }

        public Logger(string logDirDest)
		{
            this.SetLogDirDest(logDirDest);            
		}
        #endregion
        /// <summary>
        ///  写日志文件（默认路径）
        ///  应用程序当前路径下的log目录下
        /// </summary>
        /// <param name="logText">日志内容</param>
        /// <param name="lType">日志类型：log/warning/error/debug</param>
        public static void DefaultLog(string logText, LogType lType)
        {
            string fileName = string.Empty;
            switch (lType)
            {
                case LogType.Information:
                    {
                        fileName = LogDir + DateTime.Now.ToString("yyMMdd") + ".log";
                        break;
                    }
                case LogType.Warning:
                    {
                        fileName = LogDir + DateTime.Now.ToString("yyMMdd") + ".warning";
                        break;
                    }
                case LogType.Error:
                    {
                        fileName = LogDir + DateTime.Now.ToString("yyMMdd") + ".error";
                        break;
                    }
                case LogType.Debug:
                    {
                        fileName = LogDir + DateTime.Now.ToString("yyMMdd") + ".debug";
                        break;
                    }
                default:
                    {
                        fileName = LogDir + DateTime.Now.ToString("yyMMdd") + ".log";
                        break;
                    }
            }
            string[] textArray = new string[3] { DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]"), logText, "\r\n-------------\r\n" };
            logText = string.Concat(textArray);
            byte[] buffer = Encoding.UTF8.GetBytes(logText);
            FileStream stream = null;
            try
            {
                stream = File.Open(fileName, FileMode.OpenOrCreate);
                stream.Seek((long)0, SeekOrigin.End);
                stream.Write(buffer, 0, buffer.Length);
            }
            catch (Exception)
            {
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
        }
        public static void LogToDirDest(string logDirDest, string logText, LogType lType)        
		{
            if (logDirDest.Trim() != string.Empty)
			{
				string fileName = string.Empty;
				switch (lType)
				{
					case LogType.Information:
					{
						fileName = logDirDest + DateTime.Now.ToString("yyMMdd") + ".log";
						break;
					}
					case LogType.Warning:
					{
						fileName = logDirDest + DateTime.Now.ToString("yyMMdd") + ".warning";
						break;
					}
					case LogType.Error:
					{
						fileName = logDirDest + DateTime.Now.ToString("yyMMdd") + ".error";
						break;
					}
					case LogType.Debug:
					{
						fileName = logDirDest + DateTime.Now.ToString("yyMMdd") + ".debug";
						break;
					}
					default:
					{
						fileName = logDirDest + DateTime.Now.ToString("yyMMdd") + ".log";
						break;
					}
				}
				string[] textArray = new string[5]{"[",DateTime.Now.ToString(),"] ",logText,"\r\n-------------\r\n"};
				logText = string.Concat(textArray);
				byte[] buffer = Encoding.UTF8.GetBytes(logText);
				FileStream stream = null;
				try
				{
					stream = File.Open(fileName,FileMode.OpenOrCreate);
					stream.Seek((long)0,SeekOrigin.End);
					stream.Write(buffer,0,buffer.Length);
				}
				catch(Exception)
				{
				}
				finally
				{
					if(stream != null)
						stream.Close();
				}
			}
        }

        #region Logger目录设置
        public void SetLogDirDest(string logDirDest)
        {
            if (logDirDest.Substring(logDirDest.Length - 1).Equals(@"\"))
            {
                this._logdirdest = logDirDest;
            }
            else
            {
                this._logdirdest = logDirDest + @"\";
            }
        }
        #endregion

        #region 写日志
        /// <summary>
        /// test
        /// </summary>
        /// <param name="logText"></param>
        public void WriteDebugLog(string logText)
		{
			this.WriteLog(logText, LogType.Debug);
		}
 
		public void WriteErrorLog(string logText)
		{
			this.WriteLog(logText, LogType.Error);
		}

		public void WriteWarningLog(string logText)
		{
			this.WriteLog(logText, LogType.Warning);
		}
 
		public void WriteLog(string logText)
		{
			this.WriteLog(logText, LogType.Information);
		}
 

		public void WriteLog(string logText, LogType lType)
		{
			if((this._logdirdest == null) || this._logdirdest.Equals(""))
			{
				throw new Exception("日志目录没有定义或没有赋值！");
			}
            Logger.LogToDirDest(this._logdirdest, logText, lType);
        }
        #endregion

        #region 写日志Record
        /// <summary>
        /// 写日志到运行程序目录下的Logger目录中
        /// </summary>
        /// <param name="logText">日志内容</param>
        /// <param name="lType">日志类型 Information|Warning|Error|Debug</param>
        public static void Record(string logText, LogType lType)
        {
            try
            {
                string logpath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\log\\";
                if (!Directory.Exists(logpath)) Directory.CreateDirectory(logpath);

                string logfile = string.Empty;
                switch (lType)
                {
                    case LogType.Information:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".log";
                            break;
                        }
                    case LogType.Warning:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".warning";
                            break;
                        }
                    case LogType.Error:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".error";
                            break;
                        }
                    case LogType.Debug:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".debug";
                            break;
                        }
                    default:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".log";
                            break;
                        }
                }

                lock (typeof(Logger))
                {
                    FileInfo f = new FileInfo(logfile);
                    if (f.Exists)
                    {
                        using (StreamWriter w = f.AppendText())
                        {
                            w.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " | " + logText);
                        }
                    }
                    else
                    {
                        using (StreamWriter w = f.CreateText())
                        {
                            w.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " | " + logText);
                        }
                    }
                }
            }
            catch
            { }
        }
        #endregion

        #region 写日志RecordWS
        /// <summary>
        /// 写日志到运行程序目录下的Logger目录中
        /// </summary>
        /// <param name="logText">日志内容</param>
        /// <param name="lType">日志类型 Information|Warning|Error|Debug</param>
        public static void RecordWS(string logText, LogType lType)
        {
            try
            {
                //string logpath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Logger\\";
                string logpath = System.Web.HttpContext.Current.Server.MapPath(".") +"\\log\\";
                if (!Directory.Exists(logpath)) Directory.CreateDirectory(logpath);

                string logfile = string.Empty;
                switch (lType)
                {
                    case LogType.Information:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".log";
                            break;
                        }
                    case LogType.Warning:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".warning";
                            break;
                        }
                    case LogType.Error:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".error";
                            break;
                        }
                    case LogType.Debug:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".debug";
                            break;
                        }
                    default:
                        {
                            logfile = logpath + DateTime.Now.ToString("yyyyMMdd") + ".log";
                            break;
                        }
                }

                lock (typeof(Logger))
                {
                    FileInfo f = new FileInfo(logfile);
                    if (f.Exists)
                    {
                        using (StreamWriter w = f.AppendText())
                        {
                            w.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " | " + logText);
                        }
                    }
                    else
                    {
                        using (StreamWriter w = f.CreateText())
                        {
                            w.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " | " + logText);
                        }
                    }
                }
            }
            catch
            { }
        }
        #endregion

    }
}
